﻿using Beryl.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Beryl.Model
{
    public class FinishWork
    {
        private static FinishWork instance = null;
        private static readonly object uniqueLock = new object();

        public static FinishWork Instance
        {
            get
            {
                lock (uniqueLock)
                {
                    if (instance == null)
                    {
                        instance = new FinishWork();
                    }
                }
                return instance;
            }
        }

        public FinishWork() { }

        public List<string> WareHouseCode(string para)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if(para.Contains("Z21"))
                {
                    dic.Add("入库仓库", "10A0101");
                    dic.Add("入库货位", "304");
                }
                if(para.Contains("Z61"))
                {
                    dic.Add("入库仓库", "2111305");
                    dic.Add("入库货位", "305");
                }
                string jsonStr = JsonConvert.SerializeObject(dic);
                jsonStr = "[" + jsonStr + "]";
                list.Add(jsonStr);
                LogUtil.Log(name + jsonStr);
            }
            catch(Exception e)
            {
                LogUtil.Error(e.Message + name);
                list.Add(e.Message);
                return list;
            }
            return list;
        }

        //流传单查询
        public List<string> getBarCode(string para)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                string sql = string.Format(@"select a.cMOLotNo,a.cMatNo,a.cProductDepNo,a.cStatusNo,b.cCusName,
c.cWhNo,c.cMatName,c.cSpecifucation from [dbo].[APS_ProLotOrder] a join APS_PlanOrder b on a.cOrderNo = b.cPOrderNo join APS_MatData_V c on c.cMatNo = a.cMatNo where a.cBarCode='{0}'", para);
                string strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (!strPicYZ1.Equals("[]"))
                {
                    Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                    var k = jsonArr[0];
                    int status = int.Parse(k["cStatusNo"].ToString());
                    if (status < 91)
                    {
                        list.Add(strPicYZ1);
                    }
                    else
                    {
                        list.Add("批次已关闭，无需报工!");
                    }
                }
                else
                {
                    list.Add("请检查流传单!");
                }
            }
            catch (Exception e)
            {
                LogUtil.Error(name + e.Message);
                list.Add(e.Message);
            }
            LogUtil.Log(name + list[0]);
            return list;
        }

        public List<string> checkSummitData(string para)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                double topNum = 0.00;
                Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
                var k = jsonArr[0];
                int totalNum = int.Parse(k["GNumber"].ToString()) + int.Parse(k["ANumber"].ToString());
                string sql = string.Format(@"select * from PMS_ProcessPara where cProgramCode = '{0}' and cProcessCode is null", k["cProductDepNo"].ToString().Substring(1));
                var k1 = CommonMethod.Instance.selectDatabase(sql);
                var KnRow = k1.Select($"cProgramCode = '{k["cProductDepNo"].ToString().Substring(1)}'");
                var Kn1 = KnRow[0];
                double reportPercent = double.Parse(Kn1["cValue"].ToString());
                string sql1 = string.Format(@"select TotalNum,cOrderNo from APS_ValidRouting where cOrderNo = '{0}' order by ID DESC", k["cMOLotNo"].ToString());
                var k2 = CommonMethod.Instance.selectDatabase(sql1);
                var Kn2Row = k2.Select($"cOrderNo = '{k["cMOLotNo"].ToString()}'");
                double gNumber = 0.00;
                if(Kn2Row.Length > 0)
                {
                    if (Kn2Row.Length == 1)
                    {
                        var kn2 = Kn2Row[0];
                        gNumber = double.Parse(kn2["TotalNum"].ToString());
                    }
                    else
                    {
                        var kn3 = Kn2Row[1];
                    }
                    topNum = gNumber * (1 + reportPercent * 0.01);
                }
                if (topNum != 0)//末工序有报
                {
                    if (totalNum <= topNum)
                    {
                        list.Add("[1]");
                    }
                    else
                    {
                        list.Add("[报工入库数量超上限(" + topNum + ")，确认是否继续报工]");
                    }
                }else
                {
                    //list.Add("[1]");
                    list.Add("末工序未报工，请报工后再入库");
                }
            }
            catch(Exception e)
            {
                list.Add(e.Message);
                LogUtil.Error(name + e.Message);
                return list;
            }
            LogUtil.Log(name + list[0]);
            return list;
        }

        public List<string> SummitData(string para)
        {
            List<string> list = new List<string>();
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
                var k = jsonArr[0];
                string currentDate = CommonMethod.Instance.getTimes();
                bool loseEfficacy = true;
                string sql = string.Format(@"select [dbo].[fn_NewID](NEWID()) as UUID;");
                string strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                var k1 = jsonArr1[0];
                string barCode = "RM-" + k1["UUID"].ToString();
                int Category = 6;
                string sql1 = "insert into WMS_Receive (cMaterialName,cSpecifucation,cMatNo,barCode,cMOLotNo,fQuantity,dInputDate,dProductDate,createTime,loseEfficacy,cSupplier,warehousecode,cPlace,Category,cPeriod) values";
                sql1 += "('" + k["cMaterialName"].ToString() + "','" + k["cSpecifucation"].ToString() +
                           "','" + k["cMatNo"].ToString() + "','" + barCode + "','" + k["cMOLotNo"].ToString() + "','" + k["GNumber"].ToString() +
                           "','" + currentDate + "','" + currentDate + "','" + currentDate + "'," + loseEfficacy + ",'" + k["cCusName"].ToString() +
                           "','" + k["warehousecode"].ToString() + "','" + k["cPlace"].ToString() + "','" + Category + "','" + k["cPeriod"].ToString() + "');";
                string sql2 = "insert into PMS_ProductionRecord (cMOLotNo,cProQuantity,dBadNumber,cCompleteTime) values";
                sql2 += "('" + k["cMOLotNo"].ToString() + "','" + k["GNumber"].ToString() + "','" + k["ANumber"].ToString() + "','" + currentDate + "');";
                string DJlotNo = k["cMOLotNo"].ToString();

                string sql3 = string.Format(@"select cOrderNo,cBatchNumber from APS_ValidBOM where cOrderNo = '{0}'", k["cMOLotNo"].ToString());
                Newtonsoft.Json.Linq.JArray jsonArr2 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql3)));
                string updatesql = "";
                string updatesql1 = "";
                if (jsonArr2.Count == 1)
                {
                    var k2 = jsonArr2[0];
                    DJlotNo = k2["cOrderNo"].ToString();
                    updatesql = string.Format(@"update APS_ProLotOrder set cStatusNo = '0090',cPeriod = '{0}' where cMOLotNo = '{1}';", k["cPeriod"].ToString(),DJlotNo);
                }else
                {
                    updatesql += string.Format(@"update APS_ProLotOrder set cStatusNo = '0090',cPeriod = '{0}' where cMOLotNo = '{1}';", k["cPeriod"].ToString(), k["cMOLotNo"].ToString());
                }
                
                string sql5 = string.Format(@"select a.cMOLotNo,a.cStatusNo,b.cPOrderNo,c.cSourceNo from APS_ProLotOrder a join APS_PlanOrder b on a.cOrderNo = b.cPOrderNo join 
APS_PlanOandSaleORelat c on c.cPOrderNo = b.cPOrderNo where a.cOrderNo = (select cOrderNo from APS_ProLotOrder where cMOLotNo = '{0}') and a.cLotType = '1' and a.cStatusNo < '0090'", k["cMOLotNo"].ToString());
                Newtonsoft.Json.Linq.JArray jsonArr3 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql5)));

                if(jsonArr3.Count == 1 && jsonArr3[0]["cMOLotNo"].ToString().Contains(DJlotNo))
                {
                    var cPOrderNo = jsonArr3[0]["cPOrderNo"].ToString();
                    var cSourceNo = jsonArr3[0]["cSourceNo"].ToString();
                    updatesql1 += string.Format(@"update APS_PlanOrder set cStatusNo = '0090' where cPOrderNo = '{0}';update APS_SOrder set cStatusNo = '0090' where cSONo = '{1}';",cPOrderNo,cSourceNo);
                }
                string totalSql = sql1 + sql2 + updatesql + updatesql1;
                SqlHelper.IniConnString();
                var connstr = SqlHelper.GetConnSting();
                int ret = SqlHelper.ExecuteNonQuery(connstr, CommandType.Text, totalSql);
                if(ret > 0)
                {
                    list.Add("[1]");//提交成功
                    LogUtil.Log(name + list[0]);
                }
                else
                {
                    list.Add("提交失败");
                }
            }
            catch (Exception e)
            {
                list.Add(e.Message);
                return list;
            }
            return list;
        }
    }
}